<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>01.闭包实现单例模式</title>
  </head>
  <body>
    <script>
      // 立即执行函数，直接返回一个函数，使用立即执行函数和返回函数之间共用的对象形成闭包，从而在内存中保存住先前的对象以实现单例
      const Singleton = (function () {
        let instance;
        function User(name, age) {
          this.name = name;
          this.age = age;
        }
        return function (name, age) {
          if (!instance) {
            instance = new User(name, age);
          }
          return instance;
        };
      })();
    </script>
  </body>
</html>
